package tdh.xt.interceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import tdh.xt.common.utils.TokenUtil;
import tdh.xt.entity.po.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        String[] urls = new String[]{"/login.do", "/index.jsp", "/login", "/login.jsp", ".js", ".css", ".jpg", ".gif"};
        for (String url : urls) {
            if (path.endsWith(url)) {
                return true;
            }
        }
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = TokenUtil.getToken((User) request.getSession().getAttribute("loginUser"));
        }
        if (StringUtils.isEmpty(token)) {
            String realPath =
                    "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            response.sendRedirect(realPath);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
